package com.hashimoto.core.handler.decodec;
import java.util.List;

import com.hashimoto.core.message.HeartbeatPingSignal;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class HeartbeatPingSignalCodec implements Codec<HeartbeatPingSignal> {

	private int checkLength = 4;
	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out,int beginIndex) throws Exception {
		int size = in.readableBytes();
		if(checkLength > size) {
			in.readerIndex(beginIndex);
			return;
		}
		
		int dataLength = in.readInt();
		int residualLength = in.readableBytes();
		if(dataLength > residualLength) {
			in.readerIndex(beginIndex);
			return;
		}
		
		byte[] data = new byte[dataLength];
		in.writeBytes(data);
		out.add(new HeartbeatPingSignal());
	}

	@Override
	public void encode(ChannelHandlerContext ctx, HeartbeatPingSignal msg, ByteBuf out) throws Exception {
		out.writeInt(msg.getData().length);
		out.writeBytes(msg.getData());
	}

}
